﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LunchCommand.Data;
using LunchCommand.Models;

namespace LunchCommand.Controllers
{
    public class UsersController : BaseController
    {
        public UsersController()
            : base(true)
        {
        }

        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
        }

        public ActionResult Index()
        {
            return this.View(this.DatabaseContext.Users.OrderByDescending(u => u.LunchesDecided.Count(l => l.Decision)).ToArray());
        }

        // GET: Users/Edit/5
        public ActionResult Edit()
        {
            var user = this.GetUser();

            if (user == null)
            {
                return HttpNotFound();
            }

            user.Name = user.Name.Split('\\')[1];

            return View(user);
        }

        // POST: Users/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "WindowsUsername,UserId,Name")] User user)
        {
            if (ModelState.IsValid)
            {
                if (this.DatabaseContext.Users.Any(u => u.Name == user.Name))
                {
                    ModelState.AddModelError("Name", "Name already in use.  Try another");
                }
                else {
                    var actualUser = this.GetUser();

                    actualUser.Name = user.Name;

                    this.DatabaseContext.Entry(actualUser).State = EntityState.Modified;
                    this.DatabaseContext.SaveChanges();

                    return RedirectToAction("Index", "Home");
                }
            }

            return View(user);
        }

        private User GetUser()
        {
            return this.DatabaseContext.Users.Where(u => u.WindowsUsername.Equals(this.User.Identity.Name)).First();
        }
    }
}
